import { useRef, useEffect, useState } from 'react';
import * as THREE from 'three';

const VR = () => {
  const vrViewRef = useRef<HTMLDivElement>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera>();
  const [isDragging, setIsDragging] = useState(false);
  const lastPosition = useRef({ x: 0, y: 0 });
   const sceneRef=useRef()
   const rendererRef=useRef()
  // 通用旋转处理函数
  const handleRotation = (clientX: number, clientY: number) => {
    if (!cameraRef.current || !isDragging) return;

    const deltaX = clientX - lastPosition.current.x;
    const deltaY = clientY - lastPosition.current.y;

    cameraRef.current.rotation.y += deltaX * 0.002;
    cameraRef.current.rotation.x += deltaY * 0.002;

    lastPosition.current = { x: clientX, y: clientY };
  };

  // 鼠标/触摸开始
  const handleStart = (e: React.TouchEvent | React.MouseEvent) => {
    setIsDragging(true);
    if ('touches' in e) {
      lastPosition.current = {
        x: e.touches[0].clientX,
        y: e.touches[0].clientY
      };
    } else {
      lastPosition.current = {
        x: e.clientX,
        y: e.clientY
      };
    }
  };

  // 鼠标移动
  const handleMouseMove = (e: React.MouseEvent) => {
    handleRotation(e.clientX, e.clientY);
  };

  // 触摸移动
  const handleTouchMove = (e: React.TouchEvent) => {
    handleRotation(e.touches[0].clientX, e.touches[0].clientY);
  };

  // 结束操作
  const handleEnd = () => {
    setIsDragging(false);
  };

  // 初始化Three.js场景
  useEffect(() => {
    if (!vrViewRef.current) return;

    // 创建场景
    const scene = new THREE.Scene();
    sceneRef.current = scene;

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      90,
      window.innerWidth / window.innerHeight,
      0.1,
      2000 
    );
    camera.position.set(0, 0, 0); // 必须添加这行
    cameraRef.current = camera;

    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({
         antialias: true, // 开启抗锯齿
     powerPreference: "high-performance" // 高性能模式
    });
    renderer.setPixelRatio(window.devicePixelRatio); // 适配高DPI屏幕
    renderer.setSize(window.innerWidth, window.innerHeight);
    rendererRef.current = renderer;
    vrViewRef.current.appendChild(renderer.domElement);

    // 创建球体几何体
    const geometry = new THREE.SphereGeometry(500, 64, 32);
    
    // 加载纹理
    const loader = new THREE.TextureLoader();
    loader.load('/public/VR.jpg', (texture) => {
      const material = new THREE.MeshBasicMaterial({
        map: texture,
        side: THREE.DoubleSide
      });
      const mesh = new THREE.Mesh(geometry, material);
      scene.add(mesh);
    });

    // 窗口resize处理
  const handleResize = () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.render(scene, camera); // 添加这行
  };
  window.addEventListener('resize', handleResize);


    // 动画循环
    const animate = () => {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    };
    animate();

   
   

    // 清理函数
    return () => {
      
      vrViewRef.current?.removeChild(renderer.domElement);
      renderer.dispose();
    };
  }, []);

  return (
    <div
      id="myVr"
      ref={vrViewRef}
      style={{ 
        width: '100%', 
        height: '100vh', 
        display:'flex',
        justifyContent:'center',
        alignItems:'center',
        marginTop:'120px'
      
    }}
      onMouseDown={handleStart}
      onMouseMove={handleMouseMove}
      onMouseUp={handleEnd}
      onMouseLeave={handleEnd}
      onTouchStart={handleStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleEnd}
    />
  );
};

export default VR;